package com.jianying.day05;

import com.jianying.beans.WaterSensor;
import com.jianying.func.WaterSensorMapFunction;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;

import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * ClassName: Flink02_Sink_Mysql
 * Package: com.atguigu.day05
 * Description:
 *
 * @Author: tubage
 * @Create: 2024/4/3 10:03
 * @Version: 1.0
 */
public class Flink02_Sink_Mysql {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        SingleOutputStreamOperator<WaterSensor> wsDS = env.socketTextStream("localhost", 8888).map(new WaterSensorMapFunction());

        // TODO 写入MySQL
        SinkFunction<WaterSensor> jdbcSink = JdbcSink.<WaterSensor>sink(
                "insert into ws values(?,?,?)",
                new JdbcStatementBuilder<WaterSensor>() {
                    @Override
                    public void accept(PreparedStatement ps, WaterSensor ws) throws SQLException {
                        // 给问号占位符赋值
                        ps.setString(1, ws.getId());
                        ps.setLong(2, ws.getTs());
                        ps.setInt(3, ws.getVc());
                    }
                },
                JdbcExecutionOptions.builder()
                        .withBatchSize(5) // 默认5000条
                        .withBatchIntervalMs(5000L)
                        .build(),
                new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                        .withUrl("jdbc:mysql://localhost:13317/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8")
                        .withUsername("root")
                        .withPassword("123456")
                        .build()
        );
        wsDS.addSink(jdbcSink);


        env.execute();
    }
}
